package com.hzit.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzit.config.MyConverter;
import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.IClassesService;
import com.hzit.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.util.PageResult;
import com.hzit.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbxfwf
 * @since 2023-10-20
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

	// @Autowired
	// private MyConverter converter;
	@Autowired
	private IClassesService classesService;

	@Autowired
	private RedisTemplate redisTemplate;

	//1. 查询所有学生列表
	@Override
	public List<StudentVo> findAll() {
		//1.1 查询出所有的学生列表
		List<Student> list = this.list();
		//1.2 将List<Student>转换为List<StudentVo>集合
		List<StudentVo> studentVos = MyConverter.converter.toStudentVos(list);
		for (StudentVo vo : studentVos) {
			String cname = classesService.getById(vo.getCid()).getCname();
			vo.setCname(cname);
		}
		return studentVos;
	}

	//2. 分页查询
	@Override
	public PageResult<StudentVo> findByPage(Integer page, Integer pageSize) {
		//2.1 得到分页结果数据
		Page<Student> studentPage = this.lambdaQuery().page(Page.of(page, pageSize));
		//2.2 得到当前页的记录结果
		List<Student> records = studentPage.getRecords();
		//2.3 转换为List<StudentVo>对象
		List<StudentVo> studentVos = MyConverter.converter.toStudentVos(records);
		//2.4 添加每个学生的班级名称
		for (StudentVo vo : studentVos) {
			vo.setCname(classesService.getById(vo.getCid()).getCname());
		}
		//2.5 返回
		return new PageResult<>(studentPage.getTotal(),studentPage.getPages(),studentVos);
	}

	//2. 使用redis存放数据
	@Override
	public List<StudentVo> findAll2() {
		//2.1 从redis中取学生列表
		List<StudentVo> studentVos = (List<StudentVo>) redisTemplate.opsForValue().get("students");
		//2.2 此时数据库没有数据，就查询数据并放到redis中
		if(studentVos == null){
			System.out.println("正在数据数据库 。。。");
			//2.2.1 查询出所有的学生列表
			List<Student> list = this.list();
			//2.2.2 将List<Student>转换为List<StudentVo>集合
			studentVos = MyConverter.converter.toStudentVos(list);
			for (StudentVo vo : studentVos) {
				String cname = classesService.getById(vo.getCid()).getCname();
				vo.setCname(cname);
			}
			//2.2.3 将查询出来的结果放到redis中
			redisTemplate.opsForValue().set("students",studentVos,1, TimeUnit.HOURS);
		}else{
			System.out.println("缓存命中。。。");
		}

		return studentVos;
	}
}
